package be.darling.scrt.data;

import be.darling.scrt.statistics.Means;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: geert
 * Date: Nov 20, 2007
 * Time: 8:47:12 PM
 * To change this template use File | Settings | File Templates.
 */
public class Randomization {

    List<Condition> labels;
    List<Value> values;
    // todo baseline info ???
    // basic statistic data lazy instantiation
    HashMap<Condition, Means> means;


    public Randomization() {
        labels=new ArrayList<Condition>();
        values=new ArrayList<Value>();
    }

    public Randomization(List<Condition> labels, List<Value> values) {
        this.labels = labels;
        this.values = values;
    }

    public List<Condition> getLabels() {
        return labels;
    }

    public List<Value> getValues() {
        return values;
    }

    public String toString() {
        return labels.toString();
    }

    public Observation getObservation(int index){
        return new Observation(index, labels.get(index), values.get(index));
    }

    public Iterator<Observation> iterator(){
        return new Iterator(){
            int index = 0;

            public boolean hasNext() {
                return index < labels.size();
            }

            public Object next() {
                Observation o = getObservation(index);
                index++;
                return o;
            }

            public void remove() {
                // not implemented
            }
        };
    }

    // convenience methods
    public void calcMeans(){
        means = new HashMap<Condition, Means>();
        Iterator<Observation> iter = iterator();
        while (iter.hasNext()) {
            Observation observation = iter.next();
            Means m = means.get(observation.getLabel());
            if (m==null) {
                m = new Means();
                means.put(observation.getLabel(),m);
            }
            m.add(observation.getValue());
        }
    }

    public Means getMeans(String label){
        return getMeans(new Condition(label));
    }

    public Means getMeans(Condition label){
        if (means == null) calcMeans();
        return means.get(label);
    }

    public List<Observation> getObservations(Condition label){
        List<Observation> list = new ArrayList<Observation>();
        for (int i =0;i< labels.size(); i++ ) {
            Condition label1 = labels.get(i);
            if (label1.equals(label)){
                list.add(getObservation(i));
            }
        }
        return list;
    }
    public List<Value> getValues(Condition label){
        List<Value> list = new ArrayList<Value>();
        for (int i =0;i< labels.size(); i++ ) {
            Condition label1 = labels.get(i);
            if (label1.equals(label)){
                list.add(values.get(i));
            }
        }
        return list;
    }

}
